/*
 * 项目名称:    wms-server-jeecg
 * 创建人员:    hansen
 * 创建时间:    2023-09-14
 */
package org.jeecg.modules.dock.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.basic.customer.entity.BasicCustomer;
import org.jeecg.modules.basic.customer.service.IBasicCustomerService;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.basic.materialtype.entity.BasicMaterialType;
import org.jeecg.modules.basic.materialtype.service.IBasicMaterialTypeService;
import org.jeecg.modules.basic.plant.entity.WmsSapWarehouseMap;
import org.jeecg.modules.basic.plant.service.IWmsSapWarehouseMapService;
import org.jeecg.modules.basic.saplocation.entity.WmsSapLocation;
import org.jeecg.modules.basic.saplocation.service.IWmsSapLocationService;
import org.jeecg.modules.basic.supplier.entity.BasicSupplier;
import org.jeecg.modules.basic.supplier.service.IBasicSupplierService;
import org.jeecg.modules.basic.unit.entity.BasicUnit;
import org.jeecg.modules.basic.unit.service.IBasicUnitService;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouseArea;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaService;
import org.jeecg.modules.business.repertory.entity.WmsRepertory;
import org.jeecg.modules.business.repertory.service.IWmsRepertoryService;
import org.jeecg.modules.dock.client.SapRequestClient;
import org.jeecg.modules.dock.config.JsonUtils;
import org.jeecg.modules.dock.constant.SystemConstants;
import org.jeecg.modules.dock.entity.DockDataSendRecord;
import org.jeecg.modules.dock.entity.dto.request.*;
import org.jeecg.modules.dock.entity.dto.response.*;
import org.jeecg.modules.dock.enums.DockDataStatus;
import org.jeecg.modules.dock.enums.SapInterfaceTypeEnum;
import org.jeecg.modules.dock.service.IDockDataSendRecordService;
import org.jeecg.modules.dock.service.SapDockingRepeaterService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * SAP数据对接接口中转服务
 *
 * @author hansen
 * @version 1.0.0
 * @date 2023-09-14 15:29:54
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SapDockingRepeaterServiceImpl implements SapDockingRepeaterService {

    private static final String ONE = "PT01";
    private static final String TWO = "PT02";
    private static final String FOUR = "PT04";
    private static final String THREE = "PT03";
    private static final String FIVE = "PT05";
    private static final String SIX = "PT06";
    public static final String NORMAL = "normal";
    private final SapRequestClient sapRequestClient;
    private final IDockDataSendRecordService dockDataSendRecordService;
    private final IWmsSapLocationService iWmsSapLocationService;
    private final IBasicMaterialService iBasicMaterialService;
    private final IBasicCustomerService iBasicCustomerService;
    private final SysDepartMapper sysDepartMapper;
    private final IBasicUnitService iBasicUnitService;
    private final IBasicMaterialTypeService basicMaterialTypeService;
    private final IBasicMaterialTypeService iBasicMaterialTypeService;
    private final IBasicSupplierService iBasicSupplierService;
    private final IWmsSapWarehouseMapService iWmsSapWarehouseMapService;
    private final IWmsRepertoryService iWmsRepertoryService;
    private final IWmsBasicWarehouseAreaService iWmsBasicWarehouseAreaService;

    @Value("${transtella.bus.factory}")
    private String factory;

    @Override
    public List<SellOutboundResponseDTO> repeaterSapSellOutbound(List<SellOutboundRequestDTO> list) {
        List<SellOutboundResponseDTO> resList = new ArrayList<>();
        // 记录同步数据
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(SapInterfaceTypeEnum.SALE_OUTBOUND_POST.getCode());
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {

            SellOutboundResponseDTO sapSellOutbound = sapRequestClient.sapSellOutbound(SapInterfaceTypeEnum.SALE_OUTBOUND_POST.getCode(), JsonUtils.toJson(list));
            resList.add(sapSellOutbound);
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(resList));
            log.info("销售出库过账接口发送成功");
        } catch (Exception e) {
            log.info("销售出库过账接口出现异常, 数据id: {}, 时间: {}", sendRecord.getUuid(), DateUtil.date(), e);
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());

            SellOutboundResponseDTO sapSellOutbound = new SellOutboundResponseDTO();
            sapSellOutbound.setResult("E");
            sapSellOutbound.setMessage("成品UB单收货接口出现异常");
            resList.add(sapSellOutbound);
        } finally {
            dockDataSendRecordService.save(sendRecord);
            return resList;
        }
    }

    @Override
//    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public List<ProductReceptionResponseDTO> repeaterSapProductHarvest(List<ProductReceptionRequestDTO> list) {
        List<ProductReceptionResponseDTO> resList = new ArrayList<>();
        // 记录同步数据
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(SapInterfaceTypeEnum.PRODUCT_UB_RECEIVE.getCode());
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            resList = sapRequestClient.sapProductHarvest(SapInterfaceTypeEnum.PRODUCT_UB_RECEIVE.getCode(), JsonUtils.toJson(list));
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(resList));
            log.info("成品UB单收货接口发送成功");
        } catch (Exception e) {
            log.info("成品UB单收货接口出现异常, 数据id: {}, 时间: {}", sendRecord.getUuid(), DateUtil.date(), e);
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());

            ProductReceptionResponseDTO productReceptionResponseDTO = new ProductReceptionResponseDTO();
            productReceptionResponseDTO.setResult("E");
            productReceptionResponseDTO.setMessage("成品UB单收货接口出现异常");
            resList.add(productReceptionResponseDTO);
        } finally {
            dockDataSendRecordService.save(sendRecord);
            return resList;
        }
    }

    @Override
    public List<SapBaseResponseDTO> repeaterSapResearchGet(List<ResearchGetRequestDTO> list) {
        List<SapBaseResponseDTO> resList = new ArrayList<>();
        // 记录同步数据
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(SapInterfaceTypeEnum.RD_RECEIPT.getCode());
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            resList = sapRequestClient.sapResearchGet(SapInterfaceTypeEnum.RD_RECEIPT.getCode(), JsonUtils.toJson(list));
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(resList));
            log.info("研发领料接口发送成功");
        } catch (Exception e) {
            log.info("研发领料接口出现异常, 数据id: {}, 时间: {}", sendRecord.getUuid(), DateUtil.date(), e);
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());

            SapBaseResponseDTO sapSellOutbound = new SapBaseResponseDTO();
            sapSellOutbound.setResult("E");
            sapSellOutbound.setMessage("研发领料接口出现异常");
            resList.add(sapSellOutbound);
        } finally {
            dockDataSendRecordService.save(sendRecord);
            return resList;
        }
    }

    @Override
    public List<ProductReceptionResponseDTO> constructionReceiving(List<ProductReceptionRequestDTO> list) {
        List<ProductReceptionResponseDTO> resList = new ArrayList<>();
        // 记录同步数据
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(SapInterfaceTypeEnum.STRUCT_AND_CLIPS_UB_RECEIVE.getCode());
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            resList = sapRequestClient.sapProductHarvest(SapInterfaceTypeEnum.STRUCT_AND_CLIPS_UB_RECEIVE.getCode(), JsonUtils.toJson(list));
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(resList));
            log.info("结构件/夹件UB单收货接口发送成功");
        } catch (Exception e) {
            log.info("结构件/夹件UB单收货接口出现异常, 数据id: {}, 时间: {}", sendRecord.getUuid(), DateUtil.date(), e);
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());

            ProductReceptionResponseDTO sapSellOutbound = new ProductReceptionResponseDTO();
            sapSellOutbound.setResult("E");
            sapSellOutbound.setMessage("结构件/夹件UB单收货接口出现异常");
            resList.add(sapSellOutbound);
        } finally {
            dockDataSendRecordService.save(sendRecord);
            return resList;
        }
    }

    @Override
    public List<IngredientsGetResponseDTO> sapIngredientsGet(List<IngredientsGetRequestDTO> list) {
        List<IngredientsGetResponseDTO> resList = new ArrayList<>();
        // 记录同步数据
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(SapInterfaceTypeEnum.SUBSIDIARY_OUTBOUND.getCode());
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            resList = sapRequestClient.sapIngredientsGet(SapInterfaceTypeEnum.SUBSIDIARY_OUTBOUND.getCode(), JsonUtils.toJson(list));
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(resList));
            log.info("辅料成本中心领用接口发送成功");
        } catch (Exception e) {
            log.info("辅料成本中心领用接口出现异常, 数据id: {}, 时间: {}", sendRecord.getUuid(), DateUtil.date(), e);
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());

            IngredientsGetResponseDTO sapSellOutbound = new IngredientsGetResponseDTO();
            sapSellOutbound.setResult("E");
            sapSellOutbound.setMessage("辅料成本中心领用接口出现异常");
            resList.add(sapSellOutbound);
        } finally {
            dockDataSendRecordService.save(sendRecord);
            return resList;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public MasterDataResponseDTO sapMaster(MasterDataRequestDTO dto) {
        String code = SapInterfaceTypeEnum.MAIN_DATA.getCode();
        // 记录同步数据
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(dto));

        List<MasterDataRequestDTO> dtoList = new ArrayList<>(16);
        dtoList.add(dto);
        try {
            MasterDataResponseDTO masterDataResponseDTO = sapRequestClient.sapMaster(code, JsonUtils.toJson(dtoList));
            log.info("WMS实时接收到的数据是:{} ", masterDataResponseDTO);
            log.info("开始处理SAP业务码:{}", code);
            //成本中心
            List<MasterDataCostCenterResponseDTO> centerList = masterDataResponseDTO.getCenterList();
            /////////////////////////////////////////////////////////////////////////////////////////////

            //物料信息
            List<MasterDataMaterialResponseDTO> materialList = masterDataResponseDTO.getMaterialList();
            addMaterial(materialList, dto.getMaterialType());

            /////////////////////////////////////////////////////////////////////////////////////////////

            //库位信息
            List<MasterDataStoreResponseDTO> storeList = masterDataResponseDTO.getStoreList();
            addStore(storeList);

            /////////////////////////////////////////////////////////////////////////////////////////////

            //供应商信息
            List<MasterDataSupplierResponseDTO> supplierList = masterDataResponseDTO.getSupplierList();
            //客户信息
            List<MasterDataCustomResponseDTO> customList = masterDataResponseDTO.getCustomList();
//            syncCustomers(supplierList, customList);

            // 后面调整到这个
            syncCustomers(customList);
            syncSuppliers(supplierList);

            /////////////////////////////////////////////////////////////////////////////////////////////
            //单位信息
            List<MasterDataUnitResponseDTO> unitList = masterDataResponseDTO.getUnitList();
            syncUnits(unitList);

            /////////////////////////////////////////////////////////////////////////////////////////////
            //物料组信息  暂时用不到注释了
//            List<MasterDataMaterialGroupResponseDTO> groupList = masterDataResponseDTO.getGroupList();
//            syncGroups(groupList);

            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(masterDataResponseDTO));
            return masterDataResponseDTO;
        } catch (Exception e) {
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            log.error("同步主数据：{}", dto.getMaterialType());
            throw new JeecgBootException("主数据同步发生异常", e);
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }

    public void syncGroups(List<MasterDataMaterialGroupResponseDTO> groupList) {
        if (CollectionUtil.isEmpty(groupList)) {
            return;
        }
        log.info("开始同步物料组信息");
        List<BasicMaterialType> list = iBasicMaterialTypeService.list();

        List<BasicMaterialType> addlist = new ArrayList<>();
        List<BasicMaterialType> updateList = new ArrayList<>();

        groupList.stream().forEach(t -> {
            Optional<BasicMaterialType> first = list.stream().filter(a -> a.getCode().equals(t.getGroupCode())).findFirst();
            if (first.isPresent()) {
                BasicMaterialType materialType = first.get();
                if (!materialType.getName().equals(t.getGroupName())) {
                    materialType.setName(t.getGroupName());
                    updateList.add(materialType);
                }
            } else {
                BasicMaterialType materialType = new BasicMaterialType();
                materialType.setCode(t.getGroupCode());
                materialType.setName(t.getGroupName());
                materialType.setStatus("1");
                materialType.setSysOrgCode(factory);
                addlist.add(materialType);
            }
        });
        if (CollectionUtil.isNotEmpty(addlist)) {
            basicMaterialTypeService.saveBatch(addlist);
        }
        if (CollectionUtil.isNotEmpty(updateList)) {
            basicMaterialTypeService.updateBatchById(updateList);
        }
        log.info("结束同步物料组信息");
    }

    public void syncUnits(List<MasterDataUnitResponseDTO> unitList) {
        if (CollectionUtil.isEmpty(unitList)) {
            return;
        }
        log.info("开始同步单位信息");
        List<BasicUnit> list = iBasicUnitService.list();

        List<BasicUnit> addlist = new ArrayList<>();
        List<BasicUnit> updateList = new ArrayList<>();

        // 默认unit的初始，无记录；sap同步统一放入“默认”组下面
        String pid = "";
        if (CollectionUtil.isEmpty(list)) {
            BasicUnit basicUnit = new BasicUnit();
            basicUnit.setCode("001");
            basicUnit.setName("默认");
            basicUnit.setStatus("1");
            basicUnit.setType(1);
            iBasicUnitService.save(basicUnit);
            pid = basicUnit.getId();
        } else {
            Optional<BasicUnit> first = list.stream().sorted(Comparator.comparing(BasicUnit::getCreateTime)).findFirst();
            pid = first.get().getId();
        }
        String finalPid = pid;
        unitList.stream().forEach(t -> {
            Optional<BasicUnit> first = list.stream().filter(a -> a.getCode().equals(t.getUnit())).findFirst();
            if (first.isPresent()) {
                BasicUnit basicUnit = first.get();
                if (!basicUnit.getName().equals(t.getOutUnit())) {
                    basicUnit.setName(t.getOutUnit());
                    updateList.add(basicUnit);
                }
            } else {
                BasicUnit basicUnit = new BasicUnit();
                basicUnit.setCode(t.getUnit());
                basicUnit.setName(t.getOutUnit());
                basicUnit.setStatus("1");
                basicUnit.setPid(finalPid);
                basicUnit.setType(2);
                addlist.add(basicUnit);
            }
        });
        if (CollectionUtil.isNotEmpty(addlist)) {
            iBasicUnitService.saveBatch(addlist);
        }
        if (CollectionUtil.isNotEmpty(updateList)) {
            iBasicUnitService.updateBatchById(updateList);
        }
        log.info("结束同步单位信息");
    }

    /**
     * 同步sap库位,同步到对照表中
     *
     * @param storeList
     */
    @Transactional(rollbackFor = Exception.class)
    public void addStore(List<MasterDataStoreResponseDTO> storeList) {
        log.info("收到的库位信息:{}", storeList);
        if (CollectionUtil.isEmpty(storeList)) {
            return;
        }
        List<WmsSapLocation> list = iWmsSapLocationService.list();
        List<WmsSapLocation> updateList = new ArrayList<>(16);
        List<WmsSapLocation> addList = new ArrayList<>(16);

        storeList.stream().forEach(t -> {
            Optional<WmsSapLocation> first = list.stream().filter(
                    a -> a.getCode().equals(t.getLocation()) && a.getFactory().equals(t.getFactory())
            ).findFirst();
            if (first.isPresent()) {
                WmsSapLocation wmsSapLocation = first.get();
                if (!wmsSapLocation.getFactory().equals(t.getFactory()) || !wmsSapLocation.getName().equals(t.getLocationDescribe())) {
                    wmsSapLocation.setId(t.getFactory());
                    wmsSapLocation.setName(t.getLocationDescribe());
                    wmsSapLocation.setSysOrgCode(factory);
                    updateList.add(wmsSapLocation);
                }
            } else {
                WmsSapLocation wmsSapLocation = new WmsSapLocation();
                wmsSapLocation.setCode(t.getLocation());
                wmsSapLocation.setName(t.getLocationDescribe());
                wmsSapLocation.setFactory(t.getFactory());
                addList.add(wmsSapLocation);
            }
        });
        if (CollectionUtil.isNotEmpty(updateList)) {
            iWmsSapLocationService.updateBatchById(updateList);
        }
        if (CollectionUtil.isNotEmpty(addList)) {
            iWmsSapLocationService.saveBatch(addList);
        }
    }

    /**
     * 同步sap物料
     *
     * @param materialList
     */
    @Transactional(rollbackFor = Exception.class)
    public void addMaterial(List<MasterDataMaterialResponseDTO> materialList, String materialType) {
        log.info("收到的物料信息:{}", materialList);
        if (CollectionUtil.isEmpty(materialList)) {
            return;
        }
        List<BasicMaterial> materialNeedList = new ArrayList<>(16);

        List<BasicMaterialType> materialTypeList = basicMaterialTypeService.list();
        Map<String, BasicMaterialType> materialTypeListMap = materialTypeList.stream().collect(Collectors.toMap(t -> t.getCode(), a -> a));
        List<String> unitCodes = materialList.stream().map(t -> t.getUnit()).distinct().collect(Collectors.toList());
        Map<String, String> unitListMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(unitCodes)) {
            List<BasicUnit> unitList = iBasicUnitService.list(new LambdaQueryWrapper<BasicUnit>().in(BasicUnit::getCode, unitCodes));
            unitListMap = unitList.stream().collect(Collectors.toMap(t -> t.getCode(), a -> a.getId()));
        }
        if (CollectionUtil.isNotEmpty(materialList)) {
            for (MasterDataMaterialResponseDTO responseDTO : materialList) {
                BasicMaterial basicMaterial = new BasicMaterial();
                basicMaterial.setCode(responseDTO.getMaterial());
                basicMaterial.setName(responseDTO.getMaterialDescribe());
                BasicMaterialType basicMaterialType = materialTypeListMap.get(responseDTO.getMaterialType());
                basicMaterial.setMaterialTypeId(basicMaterialType.getId());
                basicMaterial.setSpecification(responseDTO.getProductModel());
                basicMaterial.setInspect(responseDTO.getHasExam());
                basicMaterial.setSysOrgCode(factory);
                basicMaterial.setStatus("1");
                basicMaterial.setUsed(1);
                // 查询单位
                if (ObjectUtil.isNotEmpty(unitListMap.get(responseDTO.getUnit()))) {
                    basicMaterial.setInventoryUnitId(unitListMap.get(responseDTO.getUnit()));
                }

                if ("X".equals(responseDTO.getHasExam())) {
                    basicMaterial.setInspect("4");
                }
                materialNeedList.add(basicMaterial);
            }
            // 查询的记录
            List<BasicMaterial> lists = iBasicMaterialService.list();

            List<BasicMaterial> addList = new ArrayList<>();

            materialNeedList.stream().forEach(t -> {
                Optional<BasicMaterial> basicMaterial = lists.stream().filter(a -> {
                    if (t.getCode().equals(a.getCode())) {
                        return true;
                    }
                    return false;
                }).findFirst();
                if (basicMaterial.isPresent()) {
                    BasicMaterial operateMaterial = basicMaterial.get();
                    // 及时更新
                    if (!ObjectUtil.equal(operateMaterial.getName(), t.getName())
                            || !ObjectUtil.equal(operateMaterial.getMaterialTypeId(), t.getMaterialTypeId())
                            || !ObjectUtil.equal(operateMaterial.getInventoryUnitId(), t.getInventoryUnitId())
                            || !ObjectUtil.equal(operateMaterial.getSpecification(), t.getSpecification())
                            || !ObjectUtil.equal(operateMaterial.getInspect(), t.getInspect())) {
                        operateMaterial.setName(t.getName());
                        operateMaterial.setMaterialTypeId(t.getMaterialTypeId());
                        operateMaterial.setSpecification(t.getSpecification());
                        operateMaterial.setInspect(t.getInspect());
                        operateMaterial.setInventoryUnitId(t.getInventoryUnitId());
                        iBasicMaterialService.updateById(operateMaterial);
                    }
                } else {
                    addList.add(t);
                }
            });
            iBasicMaterialService.saveBatch(addList);
        }
    }

    @Override
    public List<SapSteelCoilResponseDTO> getSapSteelCoilInfo(String type, String num) {
        String code = SapInterfaceTypeEnum.STEEL_BATCH_CALL.getCode();
        //记录信息
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(type));
        List<SapSteelCoilRequestDTO> list = new ArrayList<>(16);
        SapSteelCoilRequestDTO sapSteelCoilRequestDTO = new SapSteelCoilRequestDTO();
        sapSteelCoilRequestDTO.setType(type);
        sapSteelCoilRequestDTO.setNumber(num);
        sapSteelCoilRequestDTO.setUuid(IdUtil.fastSimpleUUID());
        list.add(sapSteelCoilRequestDTO);
        try {
            List<SapSteelCoilResponseDTO> sapSteelCoilInfo = sapRequestClient.getSapSteelCoilInfo(code, JsonUtils.toJson(list));
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(sapSteelCoilInfo));
            return sapSteelCoilInfo;
        } catch (Exception e) {
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("钢卷批次特性调用接收异常");
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }

    @Override
    public List<OriginalVolumeUbOrderTakeOverResponseDTO> getOriginalVolumeUbOrderTakeOver(List<OriginalVolumeUbOrderTakeOverRequestDTO> list) {
        String code = SapInterfaceTypeEnum.MATERIAL_UB_RECEIVE.getCode();
        //记录信息
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            //todo
            List<OriginalVolumeUbOrderTakeOverResponseDTO> takeOverResponseDTOList = sapRequestClient.getOriginalVolumeUbOrderTakeOver(code, JsonUtils.toJson(list));
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(takeOverResponseDTOList));
            return takeOverResponseDTOList;
        } catch (Exception e) {
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("原卷UB单收货接口异常", e);
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }

    @Override
    public List<PurchaseReceiptAssistResponseDTO> getPurchaseReceiptAssist(List<PurchaseReceiptAssistRequestDTO> list) {
        String code = SapInterfaceTypeEnum.OUT_RECEIVE_SUBSIDIARY.getCode();
        //记录信息
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            //todo
            List<PurchaseReceiptAssistResponseDTO> purchaseReceiptAssist = sapRequestClient.getPurchaseReceiptAssist(code, JsonUtils.toJson(list));
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(purchaseReceiptAssist));
            return purchaseReceiptAssist;
        } catch (Exception e) {
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("外购收货接口（辅材）接口异常");
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }

    @Override
    public List<PurchaseReceiptFinishProductResponseDTO> getPurchaseReceiptFinishProduct(List<PurchaseReceiptFinishProductRequestDTO> list) {
        String code = SapInterfaceTypeEnum.OUT_RECEIVE_PRODUCT_AND_MATERIAL.getCode();
        //记录信息
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            List<PurchaseReceiptFinishProductResponseDTO> purchaseReceiptFinishProduct = sapRequestClient.getPurchaseReceiptFinishProduct(code, JsonUtils.toJson(list));
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(purchaseReceiptFinishProduct));
            return purchaseReceiptFinishProduct;
        } catch (Exception e) {
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("外购收货接口（原卷/成品）接口异常");
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }

    /**
     * 同步客商信息
     */
    public void syncCustomers(List<MasterDataSupplierResponseDTO> supplierList, List<MasterDataCustomResponseDTO> customList) {
        log.info("同步客商信息：供应商={}，客户={}", supplierList, customList);
        if (CollectionUtil.isEmpty(supplierList) && CollectionUtil.isEmpty(customList)) {
            return;
        }
        List<BasicCustomer> list = new ArrayList<>();
        supplierList.stream().forEach(t -> {
            BasicCustomer basicCustomer = new BasicCustomer();
            basicCustomer.setName(t.getSupplierName());
            basicCustomer.setCode(t.getSupplierCode());
            basicCustomer.setKind("2");
            basicCustomer.setSysOrgCode(factory);
            list.add(basicCustomer);
        });

        customList.stream().forEach(t -> {
            BasicCustomer basicCustomer = new BasicCustomer();
            basicCustomer.setName(t.getCustomName());
            basicCustomer.setCode(t.getCustomCode());
            basicCustomer.setKind("1");
            basicCustomer.setSysOrgCode(factory);
            list.add(basicCustomer);
        });

        List<BasicCustomer> basicCustomers = iBasicCustomerService.list();

        List<BasicCustomer> addList = new ArrayList<>();
        List<SysDepart> sysDeparts = sysDepartMapper.selectList(null);
        String deptCode;
        if (CollectionUtil.isNotEmpty(sysDeparts)) {
            deptCode = sysDeparts.get(0).getOrgCode();
        } else {
            deptCode = "";
        }

        list.forEach(t -> {
            Optional<BasicCustomer> first = basicCustomers.stream().filter(a -> a.getCode().equals(t.getCode()) && a.getKind().equals(t.getKind())).findFirst();
            if (first.isPresent()) {
                BasicCustomer basicCustomer = first.get();
                // 判断名称是否相同，不相同则更新
                if (!basicCustomer.getName().equals(t.getName())) {
                    basicCustomer.setName(t.getName());
                    iBasicCustomerService.updateById(basicCustomer);
                }
            } else {
                t.setSysOrgCode(deptCode);
                t.setStatus("1");
                addList.add(t);
            }
        });

        // 同步，更新已有的，新增添加的。暂时不删
        iBasicCustomerService.saveBatch(addList);
    }

    public void syncCustomers(List<MasterDataCustomResponseDTO> customList) {
        log.info("同步客户信息：客户={}", customList);
        if (CollectionUtil.isEmpty(customList)) {
            return;
        }
        List<BasicCustomer> list = new ArrayList<>();

        customList.stream().forEach(t -> {
            BasicCustomer basicCustomer = new BasicCustomer();
            basicCustomer.setName(t.getCustomName());
            basicCustomer.setCode(t.getCustomCode());
            basicCustomer.setKind("1");
            basicCustomer.setSysOrgCode(factory);
            list.add(basicCustomer);
        });

        List<BasicCustomer> basicCustomers = iBasicCustomerService.list();

        List<BasicCustomer> addList = new ArrayList<>();
        List<SysDepart> sysDeparts = sysDepartMapper.selectList(null);
        String deptCode;
        if (CollectionUtil.isNotEmpty(sysDeparts)) {
            deptCode = sysDeparts.get(0).getOrgCode();
        } else {
            deptCode = "";
        }

        list.forEach(t -> {
            Optional<BasicCustomer> first = basicCustomers.stream().filter(a -> a.getCode().equals(t.getCode()) && a.getKind().equals(t.getKind())).findFirst();
            if (first.isPresent()) {
                BasicCustomer basicCustomer = first.get();
                // 判断名称是否相同，不相同则更新
                if (!basicCustomer.getName().equals(t.getName())) {
                    basicCustomer.setName(t.getName());
                    iBasicCustomerService.updateById(basicCustomer);
                }
            } else {
                t.setSysOrgCode(deptCode);
                t.setStatus("1");
                addList.add(t);
            }
        });

        // 同步，更新已有的，新增添加的。暂时不删
        iBasicCustomerService.saveBatch(addList);
    }

    public void syncSuppliers(List<MasterDataSupplierResponseDTO> supplierList) {
        log.info("同步供应商信息：供应商={}", supplierList);
        if (CollectionUtil.isEmpty(supplierList)) {
            return;
        }
        List<BasicSupplier> list = new ArrayList<>();
        supplierList.stream().forEach(t -> {
            BasicSupplier basicCustomer = new BasicSupplier();
            basicCustomer.setName(t.getSupplierName());
            basicCustomer.setCode(t.getSupplierCode());
            basicCustomer.setSysOrgCode(factory);
            list.add(basicCustomer);
        });

        List<BasicSupplier> basicSuppliers = iBasicSupplierService.list();

        List<BasicSupplier> addList = new ArrayList<>();
        List<SysDepart> sysDeparts = sysDepartMapper.selectList(null);
        String deptCode;
        if (CollectionUtil.isNotEmpty(sysDeparts)) {
            deptCode = sysDeparts.get(0).getOrgCode();
        } else {
            deptCode = "";
        }

        list.forEach(t -> {
            Optional<BasicSupplier> first = basicSuppliers.stream().filter(a -> a.getCode().equals(t.getCode())).findFirst();
            if (first.isPresent()) {
                BasicSupplier basicCustomer = first.get();
                // 判断名称是否相同，不相同则更新
                if (!basicCustomer.getName().equals(t.getName())) {
                    basicCustomer.setName(t.getName());
                    iBasicSupplierService.updateById(basicCustomer);
                }
            } else {
                t.setSysOrgCode(deptCode);
                t.setStatus("1");
                addList.add(t);
            }
        });

        // 同步，更新已有的，新增添加的。暂时不删
        iBasicSupplierService.saveBatch(addList);
    }

    @Override
    public List<MaterialBatchPeculiarityResponseDTO> materialPeculiarity(List<MaterialBatchPeculiarityDTO> list) {
        String code = SapInterfaceTypeEnum.MATERIAL_BATCH_PECULIARITY.getCode();
        //记录信息
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            //todo
            List<MaterialBatchPeculiarityResponseDTO> responseDTOS = sapRequestClient.materialPeculiarity(code, JsonUtils.toJson(list));
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(responseDTOS));
            return responseDTOS;
        } catch (Exception e) {
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("物料批次特性查询接口异常");
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }

    @Override
    public List<PaperPurchaseResponseDTO> sapPushPaperPurchase(List<PaperPurchaseRequestDTO> list) {
        String code = SapInterfaceTypeEnum.PAPER_PURCHASE_CREATE.getCode();
        //记录信息
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            //todo
            List<PaperPurchaseResponseDTO> purchaseReceiptAssist = sapRequestClient.sapPushPaperPurchase(code, JsonUtils.toJson(list));
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(purchaseReceiptAssist));
            return purchaseReceiptAssist;
        } catch (Exception e) {
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("纸筒采购订单创建接口异常:" + e);
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }

    @Override
    public SapBaseResponseDTO sendingOfMaterialTransferOrders(List<MaterialTransferOrderRequestDTO> list) {
        String code = SapInterfaceTypeEnum.BAR_MATERIAL_ALLOCATION.getCode();
        //记录信息
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            //todo
            SapBaseResponseDTO purchaseReceiptAssist = sapRequestClient.sendingOfMaterialTransferOrders(code, JsonUtils.toJson(list));
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(purchaseReceiptAssist));
            return purchaseReceiptAssist;
        } catch (Exception e) {
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("条料调拨订单发送接口异常:" + e);
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }

    @Override
    public List<InventoryUpdateResponseDTO> inventoryCountAdjustment(List<InventoryAdjustRequestDTO> list) {
        String code = SapInterfaceTypeEnum.INVENTORY_COUNT_ADJUSTMENT.getCode();
        //记录信息
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            //todo
            List<InventoryUpdateResponseDTO> inventoryUpdateResponseDTOS = sapRequestClient.inventoryCountAdjustment(code, JsonUtils.toJson(list));
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(inventoryUpdateResponseDTOS));
            return inventoryUpdateResponseDTOS;
        } catch (Exception e) {
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("库存盘点调整接口接口异常:" + e);
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }

    @Override
    public List<InventoryUpdateResponseDTO> inventoryUpdate(List<InventoryUpdateRequestDTO> list) {
        String code = SapInterfaceTypeEnum.INVENTORY_UPDATE.getCode();
        //记录信息
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            //todo
            List<InventoryUpdateResponseDTO> inventoryUpdateResponseDTOS = sapRequestClient.inventoryUpdate(code, JsonUtils.toJson(list));
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(inventoryUpdateResponseDTOS));
            return inventoryUpdateResponseDTOS;
        } catch (Exception e) {
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("库存盘点调整接口接口异常:" + e);
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }

    @Override
    public SearchPrintInfoHeadResponseDTO saleOutboundPrintInfo(SearchPrintInfoRequestDTO searchPrintInfoRequestDTO) {
        String code = SapInterfaceTypeEnum.SERACH_SALE_ORDER_PRINT.getCode();
        //记录信息
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(searchPrintInfoRequestDTO));
        try {
            SearchPrintInfoHeadResponseDTO inventoryUpdateResponseDTOS = sapRequestClient.saleOutboundPrintInfo(code, JsonUtils.toJson(searchPrintInfoRequestDTO));
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(inventoryUpdateResponseDTOS));
            return inventoryUpdateResponseDTOS;
        } catch (Exception e) {
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("库存盘点调整接口接口异常:" + e);
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }

    @Override
    public List<CustomerSuppliedMaterialResponseDTO> customerSuppliedMaterialHarvest(List<CustomerSuppliedMaterialHarvestRequestDTO> list) {
        List<CustomerSuppliedMaterialResponseDTO> resList = new ArrayList<>();
        // 记录同步数据
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(SapInterfaceTypeEnum.CUSTOMER_SUPPLIED_MATERIAL_STORED.getCode());
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(list));
        try {
            resList = sapRequestClient.customerSuppliedMaterialHarvest(SapInterfaceTypeEnum.PRODUCT_UB_RECEIVE.getCode(), JsonUtils.toJson(list));
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(resList));
            log.info("客供料收货接口发送成功");
        } catch (Exception e) {
            log.info("客供料收货接口出现异常, 数据id: {}, 时间: {}", sendRecord.getUuid(), DateUtil.date(), e);
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());

            CustomerSuppliedMaterialResponseDTO customerSuppliedMaterialResponseDTO = new CustomerSuppliedMaterialResponseDTO();
            customerSuppliedMaterialResponseDTO.setResult("E");
            customerSuppliedMaterialResponseDTO.setMessage("客供料收货接口出现异常");
            resList.add(customerSuppliedMaterialResponseDTO);
        } finally {
            dockDataSendRecordService.save(sendRecord);
            return resList;
        }
    }

    @Override
    public Object testSap(Object data, String code) {
        //记录信息
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(code);
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(data));
        try {
            //todo
            Object result = sapRequestClient.test(code, JsonUtils.toJson(data));
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(JsonUtils.toJson(result));
            return result;
        } catch (Exception e) {
            //加入接收日志
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("测试接口接口异常:" + e);
        } finally {
            dockDataSendRecordService.save(sendRecord);
        }
    }


    @Override
    public Result batchStockQuery(List<BatchStockQueryRequestDTO> dtoList) {
        List<BatchStockQueryResponseDTO> list = new ArrayList<>();
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.SAP);
        sendRecord.setBusinessCode(SapInterfaceTypeEnum.BATCH_STOCK_QUERY.getCode());
        sendRecord.setUuid(IdUtil.fastSimpleUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(dtoList));
        try {
            log.info("开始调用批次库存查询接口......");
            list = sapRequestClient.batchStockQuery(SapInterfaceTypeEnum.BATCH_STOCK_QUERY.getCode(), JsonUtils.toJson(dtoList));
            sendRecord.setSendTime(new Date());
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(ObjectUtil.isNotEmpty(list) ? JsonUtils.toJson(list) : null);
            log.info("查询完成");
            //更新库存
            if (ObjectUtil.isNotEmpty(list)) {
                list.forEach(stock -> {
                    WmsRepertory repertory = new WmsRepertory();
                    //获取对应仓库
                    WmsSapWarehouseMap map = iWmsSapWarehouseMapService.getOne(new LambdaQueryWrapper<WmsSapWarehouseMap>()
                            .eq(WmsSapWarehouseMap::getSapLocation, stock.getSapLocation())
                            .eq(WmsSapWarehouseMap::getFactory, stock.getFactory()));
                    if (ObjectUtil.isNotEmpty(map)) {
                        repertory.setWmsBasicWarehouseId(map.getWmsBasicWarehouseId());
                        List<WmsBasicWarehouseArea> areas = iWmsBasicWarehouseAreaService.list(new LambdaQueryWrapper<WmsBasicWarehouseArea>()
                                .eq(WmsBasicWarehouseArea::getWmsBasicWarehouseId, map.getWmsBasicWarehouseId()));
                        repertory.setWmsBasicWarehouseAreaId(ObjectUtil.isNotEmpty(areas) ? areas.get(0).getId() : null);
                    } else {
                        repertory.setWmsBasicWarehouseId(stock.getSapLocation());
                    }
                    repertory.setSysOrgCode("A04");
                    repertory.setBatchCode(stock.getBatchCode());
                    repertory.setStatus(NORMAL);
                    repertory.setMaterialCode(stock.getMaterialCode());
                    BasicMaterial material = iBasicMaterialService.getByCode(stock.getMaterialCode());
                    BasicUnit unit = iBasicUnitService.getOne(new LambdaQueryWrapper<BasicUnit>().eq(BasicUnit::getCode, stock.getUnit()));
                    repertory.setMaterialName(ObjectUtil.isNotEmpty(material) ? material.getName() : null);
                    repertory.setWmsBasicUnitId(ObjectUtil.isNotEmpty(unit) ? unit.getId() : stock.getUnit());
                    repertory.setMaterialId(ObjectUtil.isNotEmpty(material) ? material.getId() : null);
                    repertory.setSaleOrderCode(stock.getSaleOrderNumber());
                    repertory.setSaleOrderLineCode(stock.getSaleOrderLineNumber());
                    repertory.setStockQuantity(stock.getQuantity());
                    repertory.setUsableQuantity(stock.getQuantity());
                    repertory.setWarehouseDate(new Date());
                    repertory.setDelFlag(0);
                    iWmsRepertoryService.save(repertory);
                });
                return Result.OK("完成查询并添加库存", list);
            }
            return Result.OK("调用查询完成", list);
        } catch (Exception e) {
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("批次库存查询接口调用异常:" + e);
        }
    }
}
